// 工具函数
const formatTime = (date) => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  return `${[year, month, day].map(formatNumber).join("/")} ${[
    hour,
    minute,
    second,
  ]
    .map(formatNumber)
    .join(":")}`;
};

const formatNumber = (n) => {
  n = n.toString();
  return n[1] ? n : `0${n}`;
};

// 防抖函数
const debounce = (func, wait) => {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

// 节流函数
const throttle = (func, limit) => {
  let inThrottle;
  return function () {
    const args = arguments;
    const context = this;
    if (!inThrottle) {
      func.apply(context, args);
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
};

// 验证手机号
const validatePhone = (phone) => {
  const reg = /^1[3-9]\d{9}$/;
  return reg.test(phone);
};

// 验证邮箱
const validateEmail = (email) => {
  const reg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  return reg.test(email);
};

// 验证身份证号
const validateIdCard = (idCard) => {
  const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  return reg.test(idCard);
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return "0 Bytes";
  const k = 1024;
  const sizes = ["Bytes", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};

// 获取文件扩展名
const getFileExtension = (filename) => {
  return filename.slice(((filename.lastIndexOf(".") - 1) >>> 0) + 2);
};

// 压缩图片
const compressImage = (src, quality = 0.8) => {
  return new Promise((resolve, reject) => {
    wx.compressImage({
      src,
      quality,
      success: resolve,
      fail: reject,
    });
  });
};

// 选择图片
const chooseImage = (
  count = 1,
  sizeType = ["original", "compressed"],
  sourceType = ["album", "camera"]
) => {
  return new Promise((resolve, reject) => {
    wx.chooseMedia({
      count,
      mediaType: ["image"],
      sourceType,
      sizeType,
      success: resolve,
      fail: reject,
    });
  });
};

// 上传文件
const uploadFile = (url, filePath, name = "file", formData = {}) => {
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url,
      filePath,
      name,
      formData,
      success: resolve,
      fail: reject,
    });
  });
};

// 显示加载提示
const showLoading = (title = "加载中...") => {
  wx.showLoading({
    title,
    mask: true,
  });
};

// 隐藏加载提示
const hideLoading = () => {
  wx.hideLoading();
};

// 显示成功提示
const showSuccess = (title = "操作成功") => {
  wx.showToast({
    title,
    icon: "success",
    duration: 2000,
  });
};

// 显示错误提示
const showError = (title = "操作失败") => {
  wx.showToast({
    title,
    icon: "error",
    duration: 2000,
  });
};

// 显示确认对话框
const showConfirm = (title = "提示", content = "") => {
  return new Promise((resolve) => {
    wx.showModal({
      title,
      content,
      success: (res) => {
        resolve(res.confirm);
      },
    });
  });
};

// 深拷贝
const deepClone = (obj) => {
  if (obj === null || typeof obj !== "object") return obj;
  if (obj instanceof Date) return new Date(obj.getTime());
  if (obj instanceof Array) return obj.map((item) => deepClone(item));
  if (typeof obj === "object") {
    const clonedObj = {};
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key]);
      }
    }
    return clonedObj;
  }
};

// 生成随机字符串
const generateRandomString = (length) => {
  const chars =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let result = "";
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
};

// 计算GPA
const calculateGPA = (courses) => {
  let totalCredits = 0;
  let totalPoints = 0;

  courses.forEach((course) => {
    const credits = course.credit || 0;
    const score = course.score || 0;
    const points = scoreToPoints(score);

    totalCredits += credits;
    totalPoints += points * credits;
  });

  return totalCredits > 0 ? (totalPoints / totalCredits).toFixed(2) : 0;
};

// 分数转绩点
const scoreToPoints = (score) => {
  if (score >= 90) return 4.0;
  if (score >= 80) return 3.0;
  if (score >= 70) return 2.0;
  if (score >= 60) return 1.0;
  return 0.0;
};

module.exports = {
  formatTime,
  formatNumber,
  debounce,
  throttle,
  validatePhone,
  validateEmail,
  validateIdCard,
  formatFileSize,
  getFileExtension,
  compressImage,
  chooseImage,
  uploadFile,
  showLoading,
  hideLoading,
  showSuccess,
  showError,
  showConfirm,
  deepClone,
  generateRandomString,
  calculateGPA,
  scoreToPoints,
};
